package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.NewActionHelp;
import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.bean.VoteDetailBean;
import com.shwread.android.qysw.bean.VoteMainBean;
import com.shwread.android.qysw10000000.R;
import com.shwread.android.ui.customview.LinearListView;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

public class VoteDetailActivity extends BaseBusinessActivity {


    private TextView tvTitle;
    private ImageView ivPersion;
    private Button common_header_back;

    private TextView tVVoteDetailTitle;
    private TextView tvVoteDetailRule;
    private TextView tvVoteDetailTimeStart;
    private TextView tvVoteDetailTimeEnd;
    private TextView tvVoteDetailIntro;
    private TextView tVVote;

    private LinearListView lvVoteDetail;
    private VoteMainBean.ActivityVotingBean activityVotingBean;

    private View loadingView;
    private ImageView loadingImg;
    private AnimationDrawable animationDrawable;
    private List<VoteDetailBean> list;
    private VoteDetailAdapter adapter;

    //1文本，2图片，3视频
    private int type = -1;
    //1，实时展示，2投票后展示
    private boolean isVoteNumShow = false;//是否需要展示投票数
    private boolean isVote = false;//是否已经投票
    private boolean isEnd = false;//投票是否结束
    private ViewHolder holder = null;

    private int curSelected = 0;//当前已经选择了几个
    private int limitSelected = 0;//最多能选几个,自行设置-1为无限制
    private int voteType = -1;//判断是多选还是单选
    private String personIds = "";//投了那些人的id
    private List<String> idList = new ArrayList<>();

    private Bitmap bitmap = null;

    @Override
    public Handler getUIHandler() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vote_detail);
        Intent intent = getIntent();
        activityVotingBean = (VoteMainBean.ActivityVotingBean) intent.getSerializableExtra("voteBean");
        if (null == activityVotingBean) {
            return;
        }
        type = activityVotingBean.getVotingFashion();
        initView();
    }

    private void initView() {
        list = new ArrayList<>();
        loadingView = findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) findViewById(R.id.common_loading__img);
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText("投票详情");
        ivPersion = (ImageView) findViewById(R.id.common_header_persion);
        ivPersion.setVisibility(View.GONE);
        common_header_back = (Button) findViewById(R.id.common_header_back);
        common_header_back.setVisibility(View.VISIBLE);
        common_header_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tVVoteDetailTitle = (TextView) findViewById(R.id.tVVoteDetailTitle);
        tvVoteDetailRule = (TextView) findViewById(R.id.tvVoteDetailRule);
        tvVoteDetailTimeStart = (TextView) findViewById(R.id.tvVoteDetailTimeStart);
        tvVoteDetailTimeEnd = (TextView) findViewById(R.id.tvVoteDetailTimeEnd);
        tvVoteDetailIntro = (TextView) findViewById(R.id.tvVoteDetailIntro);
        tVVote = (TextView) findViewById(R.id.tVVote);
        lvVoteDetail = (LinearListView) findViewById(R.id.lvVoteDetail);

        tVVote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (idList.size() == 0) {
                    if (!isVote){
                        Toast.makeText(VoteDetailActivity.this, "请选择投票的人员", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    if (!isVote) {
                        for (int i = 0; i < idList.size(); i++) {
                            if (i != idList.size() - 1) {
                                personIds = personIds + idList.get(i) + ",";
                            } else {
                                personIds = personIds + idList.get(i);
                            }
                        }
                        insertVotingByUser(activityVotingBean.getId(), personIds);
                    }
                }
            }
        });

        tVVoteDetailTitle.setText(activityVotingBean.getTitle());
        String rule = "";
        //type==1单选，2多选有限制，3多选无限制
        voteType = activityVotingBean.getVotingType();
        if (voteType == 1) {
            limitSelected = 1;
            rule = rule + "单选";
        } else if (voteType == 2) {
            limitSelected = activityVotingBean.getVotingTypeNum();
            rule = rule + "多选，最多" + activityVotingBean.getVotingLimit() + "次";
        } else if (voteType == 3) {
            limitSelected = -1;
            rule = rule + "多选无限制";
        }
        //limit==1只能投一次，2每天投一次
        if (activityVotingBean.getVotingLimit() == 1) {
            rule = rule + "/只能投一次";
        } else if (activityVotingBean.getVotingLimit() == 2) {
            rule = rule + "/每天投一次";
        }
        tvVoteDetailRule.setText(rule);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            tvVoteDetailTimeStart.setText("开始\u3000" + formatter2.format(formatter.parse(activityVotingBean.getStartTime())));
            tvVoteDetailTimeEnd.setText("截止\u3000" + formatter2.format(formatter.parse(activityVotingBean.getEndTime())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        tvVoteDetailIntro.setText(activityVotingBean.getVotingDescription());

        //1实时展示，2投票后展示
        if (activityVotingBean.getVotingShow() == 1) {
            isVoteNumShow = true;
        } else {
            isVoteNumShow = false;
        }
        if (activityVotingBean.getVotingStatus() == 2) {//进行中
            isEnd = false;
        } else {//结束
            isEnd = true;
        }
        limitSelected = activityVotingBean.getVotingTypeNum();
        adapter = new VoteDetailAdapter(this, list);
        lvVoteDetail.setAdapter(adapter);
        qryVotingInfoById(activityVotingBean.getId());
    }


    class VoteDetailAdapter extends BaseAdapter {

        Context context;
        private List<VoteDetailBean> lst;

        public VoteDetailAdapter(Context context, List<VoteDetailBean> lst) {
            this.context = context;
            this.lst = lst;
        }

        @Override
        public int getCount() {
            return lst.size();
        }

        @Override
        public Object getItem(int i) {
            return lst.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {

            if (view == null) {
                holder = new ViewHolder();
                view = LayoutInflater.from(context).inflate(R.layout.item_lv_vote_detail, null);
                holder.tvName = (TextView) view.findViewById(R.id.tvName);
                holder.ivVotePic = (ImageView) view.findViewById(R.id.ivVotePic);
                holder.player_list_video = (JCVideoPlayerStandard) view.findViewById(R.id.player_list_video);
                holder.player_list_video.tinyBackImageView.setVisibility(View.GONE);
                holder.player_list_video.backButton.setVisibility(View.GONE);
                holder.player_list_video.titleTextView.setVisibility(View.GONE);
                holder.ivVoteCheckIcon = (ImageView) view.findViewById(R.id.ivVoteCheckIcon);
                holder.tvVoteDesc = (TextView) view.findViewById(R.id.tvVoteDesc);
                holder.tvVoteNum = (TextView) view.findViewById(R.id.tvVoteNum);
                holder.llVoteCheck = (LinearLayout) view.findViewById(R.id.llVoteCheck);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            final VoteDetailBean voteDetailBean = lst.get(i);
            isVote = voteDetailBean.isVote();
            holder.tvName.setText(voteDetailBean.getVotingName());
            if (isEnd) {
                holder.ivVoteCheckIcon.setVisibility(View.GONE);
            } else {
                if (isVote) {
                    holder.ivVoteCheckIcon.setVisibility(View.GONE);
                } else {
                    holder.ivVoteCheckIcon.setImageResource(R.drawable.vote_uncheck_icon);
                }
            }
            holder.llVoteCheck.setOnClickListener(new CheckClickListener(i, holder.ivVoteCheckIcon, voteDetailBean));
            if (null == voteDetailBean.getIntroduce() || voteDetailBean.getIntroduce().length() == 0) {
                holder.tvVoteDesc.setVisibility(View.GONE);
            } else {
                holder.tvVoteDesc.setVisibility(View.VISIBLE);
                holder.tvVoteDesc.setText(voteDetailBean.getIntroduce());
            }
            //判断有没有投过，，是不是展示票数字段
            if (isVoteNumShow) {
                holder.tvVoteNum.setVisibility(View.VISIBLE);
            } else {
                if (isVote) {
                    holder.tvVoteNum.setVisibility(View.VISIBLE);
                } else {
                    holder.tvVoteNum.setVisibility(View.GONE);
                }
            }
            holder.tvVoteNum.setText(Html.fromHtml("<font color='#b1b1b1'>得票数：</font><font color='#ff3030'>" + voteDetailBean.getTotalVoting() + "</font>"));
            if (type == 1) {//文本
                holder.ivVotePic.setVisibility(View.GONE);
                holder.player_list_video.setVisibility(View.GONE);
            } else {
                if (type == 2) {//图片
                    holder.ivVotePic.setVisibility(View.VISIBLE);
                    holder.player_list_video.setVisibility(View.GONE);
                    Glide.with(context)
                            .load(voteDetailBean.getVotingFileUrl())
                            .placeholder(R.drawable.bg_big_image)
                            .into(holder.ivVotePic);
                } else {//视频
                    holder.player_list_video.setUp(
                            voteDetailBean.getVotingFileUrl(),
                            JCVideoPlayer.SCREEN_LAYOUT_LIST,
                            voteDetailBean.getVotingName(), false);
                    holder.player_list_video.thumbImageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    holder.player_list_video.setVisibility(View.VISIBLE);
                    holder.ivVotePic.setVisibility(View.GONE);
                    Glide.with(context)
                            .load(voteDetailBean.getVotingFileThum())
                            .placeholder(R.drawable.bg_big_image)
                            .into( holder.player_list_video.thumbImageView);
                }
            }
            return view;
        }

        class CheckClickListener implements View.OnClickListener {

            int pos;
            ImageView iv;
            VoteDetailBean voteDetailBean;

            public CheckClickListener(int pos, ImageView iv, VoteDetailBean voteDetailBean) {
                this.pos = pos;
                this.iv = iv;
                this.voteDetailBean = voteDetailBean;
            }

            @Override
            public void onClick(View view) {
                if (!isEnd) {
                    if (!isVote){
                        if (voteDetailBean.isCheck()) {
                            iv.setImageResource(R.drawable.vote_uncheck_icon);
                            list.get(pos).setCheck(false);
                            idList.remove(idList.indexOf("" + list.get(pos).getId()));
                            if (curSelected > 0) {
                                curSelected--;
                            }
                        } else {//还要判断允许投多少票，已经选中几个了
                            if (voteType == 1) {
                                if (curSelected == 1) {
                                    Toast.makeText(VoteDetailActivity.this, "只能选择一个选项", Toast.LENGTH_SHORT).show();
                                } else {
                                    curSelected++;
                                    idList.add(lst.get(pos).getId() + "");
                                    iv.setImageResource(R.drawable.vote_checked_icon);
                                    list.get(pos).setCheck(true);
                                }
                            } else if (voteType == 2) {
                                if (curSelected == limitSelected) {
                                    Toast.makeText(VoteDetailActivity.this, "最多能选择" + limitSelected + "个选项", Toast.LENGTH_SHORT).show();
                                } else {
                                    curSelected++;
                                    idList.add(lst.get(pos).getId() + "");
                                    iv.setImageResource(R.drawable.vote_checked_icon);
                                    list.get(pos).setCheck(true);
                                }
                            } else if (voteType == 3) {
                                curSelected++;
                                idList.add(list.get(pos).getId() + "");
                                iv.setImageResource(R.drawable.vote_checked_icon);
                                list.get(pos).setCheck(true);
                            }
                        }
                    }
                }
            }
        }
    }

    class ViewHolder {
        TextView tvName;
        ImageView ivVotePic;
        JCVideoPlayerStandard player_list_video;
        TextView tvVoteDesc;
        TextView tvVoteNum;
        ImageView ivVoteCheckIcon;
//        ImageView ivVideoFlag;
        LinearLayout llVoteCheck;
    }

    private void qryVotingInfoById(int id) {

        NewActionHelp.qryVotingInfoById(this, id, new ObjectHttpResponseHandler<List<VoteDetailBean>>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("qryVotingInfoById", "qryVotingInfoById" + s);
                updateLoadingView(1);
            }

            @Override
            public void onSuccess(int i, Header[] headers, List<VoteDetailBean> voteDetailBeanList, String s) {
                Log.e("qryVotingInfoById", "qryVotingInfoById" + s);
                updateLoadingView(1);
                list.clear();
                list.addAll(voteDetailBeanList);
                adapter.notifyDataSetChanged();

                isVote = voteDetailBeanList.get(0).isVote();
                if (isVote) {
                    tVVote.setText("已投票");
                    tVVote.setBackgroundColor(Color.parseColor("#b1b1b1"));
                } else {
                    tVVote.setText("立即投票");
                    tVVote.setBackgroundColor(Color.parseColor("#e22b36"));
                }
                if (isEnd) {
                    tVVote.setText("已结束");
                    tVVote.setBackgroundColor(Color.parseColor("#b1b1b1"));
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<List<VoteDetailBean>>() {
                }.getType();
            }
        });
    }

    private void updateLoadingView(int flag) {
        switch (flag) {
            case -1:
                loadingView.setVisibility(View.VISIBLE);
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                loadingView.setVisibility(View.GONE);
                break;
        }
    }

    private void insertVotingByUser(int votingId, String participantIds) {

        NewActionHelp.insertVotingByUser(this, votingId, participantIds, new ObjectHttpResponseHandler<Object>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("insertVotingByUser", "insertVotingByUser" + s);
                updateLoadingView(1);
            }

            @Override
            public void onSuccess(int i, Header[] headers, Object voteDetailBeanList, String s) {
                qryVotingInfoById(activityVotingBean.getId());
                Log.e("insertVotingByUser", "insertVotingByUser" + s);
                updateLoadingView(1);
                Toast.makeText(VoteDetailActivity.this, "投票成功", Toast.LENGTH_SHORT).show();
                tVVote.setText("已投票");
                isVote=true;
                tVVote.setBackgroundColor(Color.parseColor("#b1b1b1"));
                adapter.notifyDataSetChanged();
            }

            @Override
            public Type getType() {
                return new TypeToken<Object>() {
                }.getType();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        } else {
            JCVideoPlayer.releaseAllVideos();
            super.onBackPressed();
        }
    }
}
